<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

消息：<input type="text" id="message">
接收者：<input type="text" id="to">
<button onclick="send()">发送</button>

<script>
    var ws = new WebSocket("ws://122.51.11.209:8090");
    //var ws = new WebSocket("ws://122.51.11.209:9501");
    //var ws = new WebSocket("ws://122.51.11.209:9604");
    //var ws = new WebSocket("ws://122.14.217.181:19385");
  
    //var ws = new WebSocket("ws://127.0.0.1:9501");
    ws.onopen = function(){
        console.log('连接成功');
    }

    //数据返回的解析
    function mycallback(data){
        var start = data.indexOf('[') // 第一次出现的位置
        var start1 = data.indexOf('{')

        if(start < 0){
            start = start1;
        }
        if(start >= 0 && start1 >= 0){
            start = Math.min(start,start1);
        }

        if(start >= 0){
            console.log(data);
            var json = data.substr(start); //截取
            var json = JSON.parse(json);
            console.log(json);
        }
    }

    ws.onmessage = function(data){
        // console.log(data.data);
        mycallback(data.data);
    }

    ws.onclose = function(){
        console.log('连接断开');
        alert("调用了断开连接");
    }

    function send()
    {
        var message = document.getElementById('message').value;
        var to = document.getElementById('to').value;
        console.log("准备给" + to + "发送数据：" + message);
        ws.send(JSON.stringify(['test',{
            to:to,
            message:message
        }])); //发送的数据必须是 ['test',数据] 这种格式
    }
</script>
</body>
</html>